/* eslint-disable eqeqeq */
// app/service/user.js
const Service = require('egg').Service;

class ItemService extends Service {
  async mutiupdate(itemarr) {
    const { ctx } = this;
    const itemarrs = itemarr?.map((it, i) => ({
      ...it,
      sort: i,
    }));
    let item;
    try {
      item = await ctx.model.Item.bulkCreate(itemarrs, {
        updateOnDuplicate: [
          'step_id',
          'sort',
          'status',
          'project_id',
          'starttime',
        ],
      });
    } catch (error) {
      item = error;
    }
    return item;
  }

  async getbyproject_id(project_id, status, tags, mine, selectuser) {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const where =
      status === '-1'
        ? {
          project_id,
        }
        : {
          project_id,
          status,
        };
    let item;
    try {
      item = await ctx.model.Item.findAll({
        where,
      });
      if (tags) {
        item = item?.filter(it => {
          return it?.dataValues.tags.some(
            item =>
              tags
                .split(',')
                .map(it => parseInt(it))
                .indexOf(item.id) !== -1
          );
        });
      }
      if (mine == true || mine == 'true') {
        item = item?.filter(it => {
          return it?.userid === decode.id;
        });
      } else if (selectuser) {
        item = item?.filter(it => {
          return parseInt(it?.userid) === parseInt(selectuser);
        });
      }
    } catch (error) {
      item = error;
    }
    return item;
  }
}

module.exports = ItemService;
